package com.sm.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sm.bo.HappyOrderBo;
import com.sm.model.HappyOrder;
import com.sm.model.HappyRequest;
import com.sm.model.User;
import com.sm.service.AppConfigService;
import com.sm.service.HappyOrderService;
import com.sm.service.HappyRequestService;
import com.sm.service.UserService;
import com.sm.util.Msg;
import com.sm.wx.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

@Controller
@RequestMapping("/happyOrder")
public class HappyOrderController {

    @Autowired
    private HappyOrderService happyOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private HappyRequestService happyRequestService;

    @Autowired
    private AppConfigService appConfigService;

    /**
     * 幸福问答--进入提问页面
     */
    @RequestMapping("/goToRequest")
    @ResponseBody
    public Msg goToRequest(){
        Double price = Double.parseDouble(appConfigService.getByKey("happy_request_price").getValue());
        return Msg.success(price);
    }


    /**
     * 创建幸福问答订单
     */
    @RequestMapping("/createOrder")
    @ResponseBody
    public Msg createOrder(HttpServletRequest request,HappyOrderBo happyOrderBo){
        if (ObjectUtil.isEmpty(happyOrderBo)||happyOrderBo.getPayType() == null|| StrUtil.isEmpty(happyOrderBo.getTitle())||StrUtil.isEmpty(happyOrderBo.getContent())){
            return Msg.fail().add("msg","参数错误");
        }
        User user = userService.selectUserById(happyOrderBo.getUserId());
        if (ObjectUtil.isEmpty(user)){
            return Msg.fail().add("msg","用户不存在");
        }
        //判断前端传来金额是否与后台配置金额一样
        if (happyOrderBo.getPrice().compareTo(new BigDecimal(appConfigService.getByKey("happy_request_price").getValue())) != 0) {
            return Msg.fail().add("msg", "支付金额有误");
        }

        if (happyOrderBo.getPrice().compareTo(BigDecimal.ZERO) == 0) {
            HappyRequest happyRequest = new HappyRequest();
            happyRequest.setRequestUser(happyOrderBo.getUserId());
            happyRequest.setTitle(happyOrderBo.getTitle());
            happyRequest.setContent(happyOrderBo.getContent());
            happyRequest.setCreateTime(new Date());
            happyRequestService.insertRequest(happyRequest);
            return Msg.success().add("msg", "免费提问成功");
        }

        AjaxResult order = happyOrderService.createOrder(request, happyOrderBo);
        return Msg.success(order);
    }
}
